//!@author denglibin
//!@date 2025/11/10 10:07
//!@desc 数据迁移

use crate::dao::mysql::mysql_dao;

///迁移数据
///@param src_url : "mysql://root:password@localhost/todos"
pub async fn data_migration(
    src_url: &str,
    dest_url: &str,
    src_table: &str,
    dest_table: &str,
) -> Result<(), Box<dyn std::error::Error>> {
    let src_conn = mysql_dao::get_conn_pool(src_url, 1).await?;
    let dest_conn = mysql_dao::get_conn_pool(dest_url, 1).await?;
    let mut count = 0;
    //创建目标表
    let create_table_sql = format!(
        "create table if not exists {} like {}",
        dest_table, src_table
    );

    mysql_dao::exec_update_sql(create_table_sql.as_str(), &dest_conn).await?;

    let mut start_id = 0_i64;
    loop {
        let query_sql = format!(
            "select id from {} where id>{} order by id asc limit 1000",
            src_table, start_id
        );
        let data = mysql_dao::select_list(query_sql.as_str(), &src_conn).await?;
        let rows = data.1;
        if rows.len() == 0 {
            break;
        }
        count += rows.len();

        start_id = rows.first().unwrap().first().unwrap().as_i64().unwrap();
        let end_id = rows.last().unwrap().first().unwrap().as_i64().unwrap();

        let insert_sql = format!(
            "insert into {}  select * from {} where id between {} and {}",
            dest_table, src_table, start_id, end_id
        );
        mysql_dao::exec_update_sql(insert_sql.as_str(), &dest_conn).await?;

        start_id = end_id;
        log::info!("start_id:{}, 进度:{}", start_id, count)
    }

    log::info!("完成，数量:{}", count);

    Ok(())
}
